import { goodsStatistics ,getCategory,goodsStatisticsDld} from '@/services/erp/api';
import { PlusOutlined,DownloadOutlined,QuestionCircleOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormInstance,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, history, SelectLang, useIntl, useModel } from '@umijs/max';
import { Button, Drawer, Input, message ,Tooltip} from 'antd';
import React, { useRef, useState } from 'react';

import FileSaver from 'file-saver';
import moment from 'moment';

var end = moment().format("YYYY-MM-DD HH:mm:ss");
var start = moment().subtract(1, "months").format("YYYY-MM-DD HH:mm:ss");

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [loadings, setLoadings] = useState<boolean>(false);
  const ref = useRef<ProFormInstance>();


  console.log('--------------------start',start);
  console.log('--------------------end',end);

  const getCata =  async () => {
    const msg = await getCategory(initialState?.currentStoreKey);
    console.log('------------', msg.data);
    return Object.values(msg.data).map(it=>{return {'label':it,'value':it}});
  }

  const columns: ProColumns<API.StockListItem>[] = [
    {
      title: "序号",
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: "分类",
      hideInTable: true,
      dataIndex: 'categoryName',
      valueType: 'select',
      request: getCata,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      valueType: 'dateTime',
      hideInTable: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      valueType: 'dateTime',
      hideInTable: true,
    },
    {
      title: '模式',
      dataIndex: 'humanTag',
      valueType: 'select',
      hideInTable: true,
      request: async () => [
        {
          label: '无人',
          value: 'nohuman',
        },
        {
          label: '有人',
          value: 'human',
        }
      ],
    },
    {
      title: "商品条码",
      dataIndex: 'barcode',
      hideInSearch:true,
    },
    {
      title: "商品名称",
      dataIndex: 'name',
      hideInSearch:true,
    },
    {
      title: "销量",
      dataIndex: 'count',
      hideInSearch:true,
    },
    {
      title: "销售额",
      dataIndex: 'total',
      valueType: 'money',
      hideInSearch:true,
    },

  ];

  const dowmloadFile = async () => {
    console.log('dowmloadFile--->', ref.current);
    setLoadings(true)
    var startTime = start
    var endTime = end
    var humanTag = ''
    var categoryName = ''

    if (ref.current && ref.current.getFieldValue('startTime')) {
      startTime = ref.current.getFieldValue('startTime').format("YYYY-MM-DD HH:mm:ss");
    }
    if (ref.current && ref.current.getFieldValue('endTime')) {
      endTime = ref.current.getFieldValue('endTime').format("YYYY-MM-DD HH:mm:ss");;
    }
    if (ref.current && ref.current.getFieldValue('humanTag')) {
      humanTag = ref.current.getFieldValue('humanTag');
    }
    if (ref.current && ref.current.getFieldValue('categoryName')) {
      categoryName = ref.current.getFieldValue('categoryName');
    }
    var param = {
      storeKey : initialState?.currentStoreKey,
      startTime: startTime,
      endTime: endTime,
    }
    if (categoryName && categoryName.length>0) {
      param = {
       ...param,
        categoryName: categoryName
      }
    }
    if (humanTag && humanTag.length>0) {
      param = {
       ...param,
       humanTag: humanTag
      }
    }
    const dlResult = await goodsStatisticsDld(param)
    console.log('dlResult-->',dlResult);
    if (dlResult && dlResult.length>0) {
      var blob = new Blob([dlResult], {type: "text/plain;charset=utf-8"});
      var filename = `销量数据${initialState?.currentStoreKey}-(${startTime}至${endTime}).csv`
      FileSaver.saveAs(blob, filename);
    }else{
      message.error('销量数据下载失败！')
    }
    setLoadings(false)
  }
  return (
    <PageContainer>
      <ProTable<API.StockListItem, API.PageParams>
        headerTitle="销量数据列表"
        rowKey="barcode"
        cardBordered
        search={{ labelWidth: 'auto', }}
        columns={columns}
        request={async (params, sorter, filter) => {
          const msg = await goodsStatistics({
            storeKey: initialState?.currentStoreKey,
            page: params.current-1,
            size: params.pageSize,
            startTime:params.startTime?params.startTime:start,
            endTime:params.endTime?params.endTime:end,
            ...params
          });
          return {
            data: msg.data,
            success: true,
            total: msg.dataSize,
          };
        }}
        formRef={ref}
        toolBarRender={() => [
          <Button key="primary" type="primary" icon={<DownloadOutlined />} shape="round"
            loading={loadings} onClick={() => dowmloadFile()}>
             导出销量数据
          </Button>,
          <Tooltip title="会导出符合上面查询条件的所有销量数据">
           <span> 提示 <QuestionCircleOutlined /></span>
          </Tooltip>,
        ]}
      />
    </PageContainer>
  );
};

export default TableList;
